package cn.tedu.tmall.passport.controller;

import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.passport.pojo.vo.UserLoginResultVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/tests")
@Api(tags = "02. 测试")
public class TestController {

    @Deprecated //表示已无效的注解
    @GetMapping("/isLogin")
    @ApiOperation("检查是否已经登录")
    @ApiOperationSupport(order = 100)
    public String isLogin(@ApiIgnore HttpSession session) {
        Object loginResult = session.getAttribute("loginResult");
        if (loginResult == null) {
            return "您当前未登录，或登录已过期！";
        }
        return "您此前已经登录，用户信息：" + loginResult;
    }

    @Deprecated
    @GetMapping("/check-authority")
    @ApiOperation("基于Session检查权限")
    @ApiOperationSupport(order = 200)
    public String checkAuthority(@ApiIgnore HttpSession session) {
        Object object = session.getAttribute("loginResult");
        if (object == null) {
            return "您当前未登录，或登录已过期！";
        }

        UserLoginResultVO loginResult = (UserLoginResultVO) object;
        List<String> permissions = loginResult.getPermissions();

        // 假设当前访问需要 /admin 权限
        if (!permissions.contains("/admin")) {
            return "您当前已经登录，但无此操作权限！";
        }

        return "检查权限，通过！" ;
    }

    @GetMapping("/authenticated")
    @ApiOperation("基于Security框架的认证")
    @ApiOperationSupport(order = 300)
    public String authenticated() {
        return "已经通过Spring Security框架的认证！";
    }

    @GetMapping("/principal")
    @ApiOperation("获取当事人信息")
    @ApiOperationSupport(order = 400)
    public String getPrincipal(@ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal) {
        return "当事人ID:" + principal.getId() + ",当事人用户名:" + principal.getUsername();
    }

    @GetMapping("/preAuthorize")
    @PreAuthorize("hasAuthority('/admin')")  //标记想要检查的权限
    @ApiOperation("基于Security框架的授权")
    @ApiOperationSupport(order = 500)
    public String preAuthorize() {
        return "已经通过Spring Security框架的授权！";
    }

}
